//观察者模式  QT中信号和槽的实现方法
//观察者有观察者和通知者两种对象  QT信号相当于通知者   槽相当于观察者
#include <string>
#include <iostream>
#include <memory>
#include <list>
//观察者的抽象类
class Observer
{
public:
    using ptr = std::shared_ptr<Observer>;
    virtual void update() = 0;
};
//通知者 类
class Notifier
{
public:
    using ptr=std::shared_ptr<Notifier>;
    Notifier(std::string name) : m_name(name) {}
    void setName(std::string name) { m_name = name; }
    std::string getName() { return m_name; }
    void attach(Observer::ptr observer)
    {
        observers.push_back(observer);
    }
    void detach(Observer::ptr observer)
    {
        observers.remove(observer);
    }
    //通知槽函数进行某种行为
    void notify()
    {
        for (const auto &item : observers)
        {
            std::cout<<"我是"<<m_name<<",赶紧工作"<<std::endl;
            item->update();
        }
    }

private:
    std::string m_name;
    std::list<Observer::ptr> observers;
};
//抽象观察者的  子类1
class EmployeeOne:public Observer
{
public:
    using ptr=std::shared_ptr<EmployeeOne>;
    EmployeeOne(const std::string& name):m_name(name){}
    virtual void update() override
    {
        std::cout<<"我是"<<m_name<<",停止看球"<<std::endl;
    }
private:
    std::string m_name;
};
//抽象观察者的  子类2
class EmployeeTwo:public Observer
{
public:
    using ptr=std::shared_ptr<EmployeeTwo>;
    EmployeeTwo(const std::string& name):m_name(name){}
    virtual void update() override
    {
        std::cout<<"我是"<<m_name<<",停止炒股"<<std::endl;
    }
private:
    std::string m_name;
};

int main(int argc, char** argv)
{
    Notifier::ptr boss(new Notifier("老板"));
    EmployeeOne::ptr employee1(new EmployeeOne("小李"));
    EmployeeTwo::ptr employee2(new EmployeeTwo("小王"));
    boss->attach(employee1);
    boss->attach(employee2);
    boss->notify();
    return 0;
}